import https from 'https'
import http from 'http'
import fs from 'fs'
import './db'
import auth from './middleware/auth'
import cross from './middleware/cross'
import error from './middleware/error'
import koaRange from 'koa-range'
import Koa from 'koa'
import koaStatic from 'koa-static'
import KoaRouter from 'koa-router'
import koaBody from 'koa-body'
import { accessLogger, logger } from './logs/logger'
import api from './api'
import path from 'path'
import sslify from 'koa-sslify'
import response from './middleware/response'
import env from './env'
import db from './middleware/db'

const app = new Koa()
const staticService = koaStatic(path.join(__dirname, './public'))
const router = new KoaRouter()
router.use('/api', api.routes())
app.proxy = true
app
	.use(cross)
	.use(koaRange)
	.use(error)
	.use(accessLogger())
	.use(staticService)
	.use(router.allowedMethods())
	.use(db)
	.use(koaBody({ multipart: true }))
	.use(response)
	.use(auth)
	.use(router.routes())

if (env.envType === 'dev') {
	http
		.createServer(app.callback())
		.listen(env.PROT, () => logger(`${env.PROTOCOL}://${env.DOMAIN_NAME}:${env.PROT}`))
		.on('error', err => logger(`${env.PROTOCOL}://${env.DOMAIN_NAME}:${env.PROT} 服务启动失败：${err}`))
}
if (env.envType === 'prod') {
	import('./ddns')
	app.use(sslify)
	https
		.createServer(
			{
				key: fs.readFileSync(path.join(__dirname, `./ssl/${env.DOMAIN_NAME}.key`)),
				cert: fs.readFileSync(path.join(__dirname, `./ssl/${env.DOMAIN_NAME}.pem`))
			},
			app.callback()
		)
		.listen(env.PROT, () => logger(`${env.PROTOCOL}://${env.DOMAIN_NAME}:${env.PROT}`))
		.on('error', err => logger(`${env.PROTOCOL}://${env.DOMAIN_NAME}:${env.PROT} 服务启动失败：${err}`))

	https
		.createServer(
			{
				key: fs.readFileSync(path.join(__dirname, `./ssl/ipv6.${env.DOMAIN_NAME}.key`)),
				cert: fs.readFileSync(path.join(__dirname, `./ssl/ipv6.${env.DOMAIN_NAME}.pem`))
			},
			app.callback()
		)
		.listen(env.IPV6_PROT, () => logger('ipv6服务启动成功'))
		.on('error', err => logger('ipv6服务启动失败：' + err))
}
